package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"helloCms/models"
	"path"
	"time"
	"os"
	"io/ioutil"
	"strings"
	"strconv"
)

type ArticleInfoController struct {
	beego.Controller
}

func (c *ArticleInfoController)Index()  {
	c.TplName="ArticleInfo/Index.html"
}

func (c *ArticleInfoController)GetArticleInfo()  {
	pageIndex,_:=c.GetInt("page")
	pageSize,_:=c.GetInt("rows")
	start:=(pageIndex-1)*pageSize
	o:=orm.NewOrm()
	articles:=make([]models.Articleinfo,0)
	o.QueryTable("articleinfo").Filter("del_flag",0).OrderBy("id").Limit(pageSize,start).All(&articles)
	count,_:=o.QueryTable("articleinfo").Filter("del_flag",0).Count()
	c.Data["json"]=map[string]interface{}{"rows":articles,"total":count}
	c.ServeJSON()
}

func (c *ArticleInfoController)ShowAddArticleInfo()  {
	o:=orm.NewOrm()
	articleClass:=make([]models.Articleclass,0)
	o.QueryTable("articleclass").Filter("parent_id__gte",1).All(&articleClass)
	c.Data["articleClass"]=articleClass
	c.TplName="ArticleInfo/ShowAddArticleInfo.html"
}

func (c *ArticleInfoController)FileUp()  {
	f,h,err:=c.GetFile("fileUp")
	defer f.Close()
	if err!=nil{
		c.Data["json"]=map[string]interface{}{"flag":"no","msg":"文件上传失败"}
		c.ServeJSON()
		return
	}
	if path.Ext(h.Filename)!=".jpg" && path.Ext(h.Filename)!=".png"{
		c.Data["json"]=map[string]interface{}{"flag":"no","msg":"文件上传格式只支持jpg和png"}
		c.ServeJSON()
		return
	}
	if h.Size>5000000{
		c.Data["json"]=map[string]interface{}{"flag":"no","msg":"文件大小不得超过5M"}
		c.ServeJSON()
		return
	}
	dir:="./static/img/Article/"+time.Now().Format("2006-01-02")+"/"
	_,err1:=os.Stat(dir)
	if err1!=nil{//表示没有文件夹。
		os.MkdirAll(dir,os.ModePerm) //和Mkdir区别是这个可以创建多个目录
	}
	fileName:=time.Now().Format("15h04m05s.000ms")//史前巨坑：windows文件名不能有冒号
	fullDir:=dir+fileName+path.Ext(h.Filename)
	//beego.Info(fullDir)
	//_, _, err= c.Ctx.Request.FormFile(fullDir)
	//if err != nil {
	//	beego.Info(err)
	//}
	err2:=c.SaveToFile("fileUp",fullDir)
	if err2!=nil{
		c.Data["json"]=map[string]interface{}{"flag":"no","msg":"文件保存失败"}
		c.ServeJSON()
		return
	}

	c.Data["json"]=map[string]interface{}{"flag":"ok","msg":fullDir}
	c.ServeJSON()
}

func (c *ArticleInfoController)AddArticle()  {
	articleInfo:=models.Articleinfo{
		DelFlag:0,
		AddDate:time.Now(),
		ArticleContent: c.GetString("ArticleContent"),
		Origin: c.GetString("Origin"),
		Title: c.GetString("title"),
		PhotoUrl: c.GetString("PhotoUrl"),
		KeyWords: c.GetString("KeyWords"),
		Intro: c.GetString("Intro"),
		Author: c.GetString("Author"),
		FullTitle: c.GetString("FullTitle"),
		ModifyDate:time.Now(),
	}
	o:=orm.NewOrm()
	num,err:=o.Insert(&articleInfo)
	if err!=nil {
		return
	}
	//获取类别编号
	classId,_:=c.GetInt("className")
	//查询类别的信息。
	var classInfo models.Articleclass
	o.QueryTable("articleclass").Filter("id",classId).One(&classInfo)
	//创建M2M对象
	m2m:=o.QueryM2M(&articleInfo,"ArticleClasses")
	_,err=m2m.Add(classInfo)
	if err!=nil {
		return
	}
	err=CreateStaticPage(int(num))//生成静态页面
	if err!=nil {
		return
	}
	c.Data["json"]=map[string]interface{}{"flag":"ok"}
	c.ServeJSON()
}

func CreateStaticPage(aId int)error  {
	//1:根据传递过来的文章编号，查询对应的文章信息
	var articleInfo models.Articleinfo
	o:=orm.NewOrm()
	o.QueryTable("articleinfo").Filter("id",aId).One(&articleInfo)
	dir:="./static/ArticleTemplate/ArticleTemplateInfo.html"
	file,err:=os.Open(dir)
	defer  file.Close()
	if err!=nil{
		beego.Info("文件打开失败")
		return err
	}else{
		//读取打开文件中的内容。
		content,_:=ioutil.ReadAll(file)
		//将读取的内容转换成文本字符串。
		articleContent:=string(content)
		articleContent=strings.Replace(articleContent,"$Title",articleInfo.Title,-1)
		articleContent=strings.Replace(articleContent,"$Origin",articleInfo.Origin,-1)
		articleContent=strings.Replace(articleContent,"$ArticleContent",articleInfo.ArticleContent,-1)
		articleContent=strings.Replace(articleContent,"$AddDate",articleInfo.AddDate.Format("2006-01-02"),-1)
		//创建文件夹。
		//month:=articleInfo.AddDate.Format("01")
		//beego.Info(month)
		dirDict:="./static/Article/"+string(articleInfo.AddDate.Format("2006-01-02"))+"/"
		_,err:=os.Stat(dirDict)
		if err!=nil{
			os.MkdirAll(dirDict,os.ModePerm)
		}
		fullDir:=dirDict+strconv.Itoa(articleInfo.Id)+".html"
		if ioutil.WriteFile(fullDir,[]byte(articleContent),0644)==nil{
			beego.Info("写入文件成功")
		}
		return nil

		//var m int
		//for i:=0;i<len(months) ; i++ {
		//	if months[i]==month {
		//		m=i
		//		break
		//	}
		//}
		//m=m+1
		//beego.Info(m)
		//var dirDict string
		//if m<10{
		//	md:="0"+strconv.Itoa(m)
		//	beego.Info(md)
		//	dirDict="./static/Article/"+strconv.Itoa(articleInfo.AddDate.Year())+"/"+md+"/"+strconv.Itoa(articleInfo.AddDate.Day())+"/"
		//}else{
		//	dirDict="./static/Article/"+strconv.Itoa(articleInfo.AddDate.Year())+"/"+strconv.Itoa(m)+"/"+strconv.Itoa(articleInfo.AddDate.Day())+"/"
		//}
		//_,err:=os.Stat(dirDict)
		//if err!=nil{
		//	os.MkdirAll(dirDict,os.ModePerm)
		//}
		//fullDir:=dirDict+strconv.Itoa(articleInfo.Id)+".html"
		//if ioutil.WriteFile(fullDir,[]byte(articleContent),0644)==nil{
		//	beego.Info("写入文件成功")
		//}
		//return nil
	}
}

//定义日期切片
//var months = []string{
//	"January",
//	"February",
//	"March",
//	"April",
//	"May",
//	"June",
//	"July",
//	"August",
//	"September",
//	"October",
//	"November",
//	"December",
//}